package com.moon.interview.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.moon.interview.model.entity.BaseEntity;
import com.moon.interview.model.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Objects;

import static com.moon.interview.constant.UserConstant.USER_LOGIN_STATE;

/**
 * MyBatis plus配置
 * @author MoonX
 */
@Configuration
@MapperScan("com.moon.interview.mapper")
public class MyBatisPlusConfig {
    private static final Long DEFAULT_USER = 0L;

    @Autowired
    HttpServletRequest request;

    /**
     * 自动填充BaseModel字段
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            /**
             * 新增策略
             */
            @Override
            public void insertFill(MetaObject metaObject) {
                if (!Objects.isNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
                    Date date = new Date();
                    // 创建时间和更新时间
                    baseEntity.setCreateTime(date);
                    baseEntity.setUpdateTime(date);
                    // 创建人和更新人
                    baseEntity.setCreateBy(getUserId());
                    baseEntity.setUpdateBy(getUserId());
                    // 删除标志  0 - 未删除
                    baseEntity.setIsDelete(0);
                }
            }
            /**
             * 更新策略
             */
            @Override
            public void updateFill(MetaObject metaObject) {
                if (!Objects.isNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
                    Date date = new Date();
                    // 更新时间
                    baseEntity.setUpdateTime(date);
                    // 更新人
                    baseEntity.setUpdateBy(getUserId());
                }
            }
        };

    }

    /**
     * 获取当前登录用户的Id
     * @return
     */
    public Long getUserId(){
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            return DEFAULT_USER;
        }
        User user = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        return user.getId();
    }
}
